import { Button, Space, Toast, Form, DotLoading, Modal } from "antd-mobile";
import { appNavigate, appTypeCheck, checkENV, checkENV2 } from "@/utils";
import requewt from "@/utils/requewt";
import { API, MINI_P_PATH, REDIRECT_TITLE, REDIRECT_WX_COVER, REDIRECT_WX_URL } from "@/config";
import { useEffect, useReducer, useRef, useState } from "react";
import callFeedback from "@/components/common/modalFeedback";
import { KvHeaderComp, KvContentComp, KvBrandComp } from "@/components/common";
import Router, { useRouter } from "next/router";
import { signIn, signOut } from "next-auth/react";
import { useCookies } from "react-cookie";
import * as gtag from '@/libs/gtag'
import useRecord from "@/components/pages/stores/useRecord";
import useApp from "@/stores/useApp";

const pageName = "home";
const klassName = pageName.replace(/\./g, '-');

const LANDING_URL = `/landing`;
const TEST_TOKEN = `SytIUWlFa0Z1VFpLaUtsdnZvbFhJYWNoblZWNzEvS0lXQ0tKVXpGTE93K0pybi9nR0dqNEs5RXRTemRMSXVKZ2IwMGZrVHFLMGdyR2hkWlpxalpmb1E9PQ--___1709779727803___264502___2982696681___WECHAT`

const ENV_MAP = {
  mini: {
    title: `小程序`,
    key: `mini`
  },
  app: {
    title: `APP`,
    key: `app`
  },
  test: {
    title: `测试`,
    key: `test`
  }
}

export default function Page(props) {
  const [env, setENV] = useState(undefined);
  const [loading, setLoading] = useState(true);
  const [cookies, setCookie] = useCookies(['name']);
  const [error, setError] = useState(undefined);
  const [envName, setENVName] = useState(undefined);
  const [showTest, setShowTest] = useState(false);

  const updateENV = useApp(state => state.updateENV);
  let timer, flag = 0;

  const compHandler = {
    login: async (body) => {
      const options = {
        method: `POST`,
        headers: { "Content-Type": "multipart/form-data" },
        body
      }
      console.log(`登录参数：${JSON.stringify(body)}`)
      const resp = await requewt(API.user.login, options).catch((error) => {
        console.error('登录失败：', error)
        global?.activity.toLogin()
      });
      console.log('登录接口：',resp)
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
        callFeedback({
          title: <div dangerouslySetInnerHTML={{ __html: resp?.msg || `登入失败!` }}>
          </div>,
          actions: [
            <Button key={`close`} onClick={e => {
              if (env === `mini`) {
                wx?.miniProgram?.navigateBack()
              } else if (env === `app`) {
                if (window.QYApp.closePage) {
                  window?.QYApp?.closePage()
                } else {
                  global?.QYApp.closeView()
                }
              }
            }} size="small"
              className="act-btn act-btn-primary">确认</Button>
          ]
        })
        return null
      }
      const { token } = resp?.data;
      console.log(`登录成功：${token}`)
      setCookie('auth', token, { path: `/`, maxAge: 3600 * 24 * 7 });
      sessionStorage.setItem('auth', token)
      if (global.activity?.aid) {
        requewt(API.user.userInvite, {method:'POST',headers: { "Content-Type": "multipart/form-data" },body: {aid:window.activity?.aid}})
      }
      global.$uni_h5_auth = token
      const resolve = await signIn("credentials", { token, position: body.source, redirect: false });
      // console.log(`resolve`, resolve)
      // Modal.alert({
      //   content: '登录成功',
      //   onConfirm() {
      //      Router.push(LANDING_URL);
      //   },
      //   showCloseButton: false
      // })
      await Router.push(LANDING_URL);
      return token

    },
    testing: async () => {
      // useMap.mini.auth()
      // const uni_auth = QYApp?.getToken();
      // const userInfo = QYApp?.getUserInfo()
      // console.log('userinfo',userInfo)
      // console.log('token',uni_auth)
      // console.log(Router.query, 'query')
      let query = {
        token:'SytIUWlFa0Z1VFpLaUtsdnZvbFhJYWNoblZWNzEvS0lXQ0tKVXpGTE93K0pybi9nR0dqNEs5RXRTemRMSXVKZ2IwMGZrVHFLMGdyR2hkWlpxalpmb1E9PQ--___1709779727803___264502___2982696681___WECHAT',
        source:'mini',
        position: 'mini'
      }
      if(Router.query.token) {
        query = Router.query
      }

      const {  token: UNIAuth, source,position } = query
      const token = await compHandler.login({
        UNIAuth,  source, position,
      })
      // if (!token) return
      // await setCookie('auth', token, { path: `/`, maxAge: 3600 * 24 * 7 });

      // signIn("credentials", { token, position: 'test', redirect: false });
      // // console.log(Router.query)
      // await Router.push(LANDING_URL)
    },
  }

  useEffect(() => {
    (async () => {
      
      setLoading(true);
      await waitForAuth();
      
    })()
  }, [])
  useEffect(() => {
    
    if (!ENV_MAP[env]) return setError(`请使用极狐小程序打开参与活动!`);
    else setError(undefined);
    // if (env&&env !== 'app') {
    //   return setError('请在启源APP中打开')
    // }
    if (env === `mini`) {
      const data = {
        title: REDIRECT_TITLE, // 分享标题
        path: MINI_P_PATH,
        imageUrl: REDIRECT_WX_COVER
      }
      wx?.miniProgram.postMessage({ data: {
        shareParams: data
      } })
      console.log('window对象token：',global.activity.token)
      if (!global?.activity.token) {
        global.activity.toLogin()
        return
      }
    }
    
    updateENV(env);
    setENVName(ENV_MAP[env].title);
    useMap[env].auth()
    // setTimeout(() => , 1000)
  }, [env])

  const useMap = {
    mini: {
      auth: async e => {
        let { token: UNIAuth,position="mini" } = Router.query || global.activity?.token;
        console.log(`小程序进入系统参数：${global.location.href}`)
        console.log(global)
        if (!UNIAuth) {
          global.activity.toLogin()
          return
        }

        gtag.event({
          action: 'mini_login',
          category: 'Login',
          label: `${position}`,
        })
        
        
        const values = { UNIAuth, source: `mini`,position: position };

        await compHandler.login(values, async () => {
          // await Router.push(LANDING_URL)
          
        });
      }
    },
    app: {
      auth: async e => {
        const { position ='unknown' } = Router.query || {};
        const uni_token = window.QYApp?.getToken();
        const userInfo = window.QYApp?.getUserInfo() 
        console.log('userinfo', userInfo)

        gtag.event({
          action: 'app_login',
          category: 'Login',
          label: `${position}`,
        })
        const {mobilePhone:phone,token:UNIAuth,regTime:reg_time,nickname:name,userId:ca_user_id } = JSON.parse(userInfo)
        const values = { UNIAuth,phone,name,reg_time, extra: userInfo,ca_user_id, source: `app`,position }
        await compHandler.login(values);
      }
    },
    test: {
      auth: async e => {
        const { position } = Router.query || {};
        const values = { UNIAuth: TEST_TOKEN, source: `test`, position:'test' }
        gtag.event({
          action: 'test_login',
          category: 'Login',
          label: `${position}`,
        })

        await compHandler.login(values, async () => {
          // await Router.push(LANDING_URL,{query:{...Router.query}})
        });
      }
    }
  }

  const wait4Auth = async (ev) => {
    const resp = await checkENV2();
    updateENV(resp);
    setENV(resp)
  }

  const waitForAuth = async (ev) => {
    if (flag >= 30) {
      setLoading(false);
      setShowTest(`未检测到正式环境`);
      // Toast.show({duration: 3000, content: `授权失败！请保证网络畅通、并在引力域的APP或小程序中打开`});
      return
    }
    setTimeout(() => {
      if (ev) {
        setENV(ev);
        setLoading(false);
        return;
      }
      flag++;
      const resolve = checkENV();
      // console.log(`resolve`, resolve)
      waitForAuth(resolve);
    }, 100);
  };

  return (
    <>
      <div className={`p-${klassName} page page-start`}>
        <div className="inner">
          <KvBrandComp />

          <div className="position-center">

            <div className="kv-footer text-center" style={{ color: `#fff` }}>
              {
                [`mini`, `app`].includes(env) ?
                  <>
                    <DotLoading color='white' /> <span>{ENV_MAP[env].title} 登入中</span>
                  </>
                  :
                  showTest ?
                    <Space direction={`vertical`}>
                      {/* <span>{showTest}</span> */}
                      <span style={{color:'#000'}}>{error}</span>
                      {/* <Button onClick={compHandler.testing}>测试登入</Button> */}
                    </Space>
                    :
                    <DotLoading color='white' />
              }
            </div>
          </div>
        </div>
      </div>

    </>

  )
}


Page.need2auth = false;
Page.pageName = pageName;